package com.sixth.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixth.dao.ShoucangTeacherDao;
import com.sixth.dao.TbMemberDao;
import com.sixth.entity.TableResult;
import com.sixth.entity.TbMember;
import com.sixth.service.MemberService;

import com.sixth.until.CommonResult;
import com.sixth.until.OrderNoUtil;
import com.sixth.until.WebUtil;
import com.sixth.vo.LoginVo;
import com.sixth.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @program: self-tui-education
 * @description:
 * @author: 厉泽禄
 * @create: 2022-04-15 19:02
 **/
@Service(value = "memberService")
public class MemberServiceImpl implements MemberService {
    @Autowired
    private TbMemberDao memberDao;
    @Autowired
    private PasswordEncoder passwordEncoder;//密码加密器
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ShoucangTeacherDao shoucangTeacherDao;
    @Bean //创建一个密码加密器的对象交于spring容器来管理
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    public TableResult getStudentAll(Integer pageNum, Integer pageSize, MemberVo memberVo) {
        PageHelper.startPage(pageNum,pageSize);
        String mobile = memberVo.getMobile();
        String nickname = memberVo.getNickname();
        Date[] gmtCreate = memberVo.getGmtCreate();
        String isDisabled = memberVo.getIsDisabled();
        String startTime=null;
        String stopTime=null;
        if(gmtCreate.length!=0){
            Date date = gmtCreate[0];
            Date date1 = gmtCreate[1];
            String s1 = date + "";
            String s2 = date1 + "";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date format1 = new Date(s1);
                Date format2 = new Date(s2);
                String start = format.format(format1);
                String stop = format.format(format2);
                startTime = format.parse(start).toLocaleString();
                stopTime = format.parse(stop).toLocaleString();
                //System.out.println(startTime);
                //System.out.println(stopTime);
                List<TbMember> members=memberDao.getStudentAll(mobile,nickname,startTime,stopTime,isDisabled);
                PageInfo<TbMember> pageInfo = new PageInfo<>(members);
                return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<TbMember> members=memberDao.getStudentAll(mobile,nickname,startTime,stopTime,isDisabled);
        PageInfo<TbMember> pageInfo = new PageInfo<>(members);
        return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
    }
    @Override
    public CommonResult stateChange(Boolean isDisabled, String id) {
        String state=null;
        if(isDisabled){
            state="1";
        }
        if(!isDisabled){
            state="0";
        }
        int row=memberDao.stateChange(state,id);
        if(row>0){
            return new CommonResult(2000,"禁用成功",null);
        }
        return new CommonResult(5000,"禁用失败",null);
    }
    @Override
    public CommonResult updateInfo(TbMember member) {
        String id = member.getId();
        String nickname = member.getNickname();
        String age = member.getAge() + "";
        String avatar = member.getAvatar();
        String sex = member.getSex() + "";
        String remark = member.getRemark();
        int row = memberDao.updateInfo(id, nickname, sex, remark, age, avatar);
        if (row > 0) {
            return new CommonResult(2000, "修改成功", null);
        }
        return new CommonResult(5000, "修改失败", null);
    }
    @Override
    public CommonResult qianLogin(LoginVo loginVo) {
        QueryWrapper<TbMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",loginVo.getMobile());
        TbMember member1 = memberDao.selectOne(wrapper);
        if(member1!=null){
            String password = member1.getPassword();
            boolean matches = passwordEncoder.matches(loginVo.getQianPassword(),password);
            if(matches){
                //生成token.
                Date nowDate=new Date();
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.SECOND,7200);
                Date expire = calendar.getTime(); //过期时间
                Map<String,Object> head=new HashMap<>();
                head.put("alg","HS256");
                head.put("typ","JWT");
                String token = JWT.create()
                        .withHeader(head)
                        .withIssuedAt(nowDate)
                        .withExpiresAt(expire)
                        .withClaim("id",member1.getId())
                        .withClaim("nickname", member1.getNickname()) //你把用户的什么信息存放token中 存入用户名
                        .withClaim("mobile",member1.getMobile())
                        .sign(Algorithm.HMAC256("gzy-lpp"));//加密方式

                redisTemplate.opsForValue().set(token,"",24*60*60, TimeUnit.SECONDS);
                List<String> teachers=shoucangTeacherDao.findTeacher(member1.getId());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("token",token);
                hashMap.put("isTeacher",member1.getIsType());
                hashMap.put("mobile",member1.getMobile());
                hashMap.put("id",member1.getId());
                return new CommonResult(2000,"登录成功",hashMap);
            }
            return new CommonResult(5000,"密码错误",null);
        }
        return new CommonResult(5000,"登录失败",null);
    }
    //生成密码
    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
    }
    @Override
    public CommonResult findStudentBymobile(String mobile) {
        QueryWrapper<TbMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        TbMember member = memberDao.selectOne(wrapper);
        return new CommonResult(2000,"查询成功",member);
    }
    @Override
    public CommonResult tuichuLogin() {
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        return new CommonResult(2000,"退出成功",null);
    }
    @Override
    public CommonResult getYanZhengMa(String mobile) {
        String data="123456";
        return new CommonResult(2000,"获取成功",data);
    }
    @Override
    public CommonResult installMember(String mobile, String qianPassword) {
        QueryWrapper<TbMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        TbMember member = memberDao.selectOne(wrapper);
        if(member!=null){
            return new CommonResult(2000,"该手机号已经注册",null);
        }
        TbMember installMember = new TbMember();
        String orderNo = OrderNoUtil.getOrderNo();
        installMember.setId(orderNo);
        installMember.setMobile(mobile);
        String encode = passwordEncoder.encode(qianPassword);
        installMember.setPassword(passwordEncoder.encode(qianPassword));
        installMember.setIsType(0);
        installMember.setIsDisabled(false);
        installMember.setIsDeleted(false);
        Date date = new Date();
        installMember.setGmtCreate(new Date());
        int row = memberDao.insertMy(orderNo,mobile,encode,"0",false,false,date);
        if(row>0){
            return new CommonResult(2000,"注册成功",null);
        }
        return null;
    }
    @Override
    public CommonResult oss(MultipartFile file) {
        try {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = "LTAI5tPrKSeCqxhuwYQ4um9r";
            String accessKeySecret = "3uilVugK9cQFB5rQUUpEJZye4IoLVs";

// 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String filename = file.getOriginalFilename();
            filename = new Date().getTime() + filename;
// 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject("apricity01", filename, inputStream);

// 关闭OSSClient。
            ossClient.shutdown();
            String url="https://apricity01."+endpoint+"/"+filename;
            return new CommonResult(2000,"上传成功",url);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new CommonResult(5000,"上传失败",null);
    }
}
